<template>
  <div class="app-container">
    <div v-if="step === 1">
      <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="168px">
        <el-form-item label="编号" prop="item_no">
          <el-input
            v-model="queryParams.item_no"
            placeholder="请输入编号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="消耗品名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入消耗品名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="数量" prop="qty">
          <el-input
            v-model="queryParams.qty"
            placeholder="请输入数量"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="采购日期" prop="purchase_date">
          <el-date-picker
            v-model="queryParams.purchase_date"
            clearable
            size="small"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择采购日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="采购价格" prop="purchase_cost">
          <el-input
            v-model="queryParams.purchase_cost"
            placeholder="请输入采购价格"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="订单编号" prop="order_number">
          <el-input
            v-model="queryParams.order_number"
            placeholder="请输入订单编号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="最小数量" prop="min_amt">
          <el-input
            v-model="queryParams.min_amt"
            placeholder="请输入最小数量"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="型号" prop="model_number">
          <el-input
            v-model="queryParams.model_number"
            placeholder="请输入型号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['admin:assets:consumables:post']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['admin:assets:consumables:put']"
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['admin:assets:consumables:delete']"
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['admin:assets:assets:export']"
            type="primary"
            plain
            icon="el-icon-position"
            size="mini"
            :loading="exportLoading"
            @click="handleInput"
          >导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['admin:assets:consumables:export']"
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            :loading="exportLoading"
            @click="handleExport"
          >导出</el-button>
        </el-col>
        <right-toolbar :show-search.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="consumablesList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column width="155" label="消耗品名称" align="center" prop="name"  sortable >
          <template slot-scope="scope">
            <el-link type="primary" @click="clickAssets(scope)">{{ scope.row.name }}</el-link>
          </template>
        </el-table-column>
        <el-table-column width="155" label="分类" align="center" prop="category_name"  sortable />
        <el-table-column width="155" label="型号" align="center" prop="model_number"  sortable />
        <el-table-column width="155" label="项目编号" align="center" prop="item_no"  sortable />
        <el-table-column width="155" label="总共数量" align="center" prop="qty"  sortable />
        <el-table-column width="200" label="位置" align="center" prop="location_name"  sortable />
        <el-table-column width="155" label="剩余数量" align="center"  sortable>
          <template slot-scope="scope">
             <span>{{scope.row.qty - scope.row.checkout_qty}}</span>
          </template>
        </el-table-column>
        <el-table-column width="155" label="最小数量" align="center" prop="min_amt"  sortable />
        <el-table-column width="155" label="是否可申请" align="center" prop="requestable"  sortable >
          <template slot-scope="scope">
            <img v-if="scope.row.requestable" src="../../../../assets/images/dui.png" style="width: 20px;height: 20px" />
            <img v-if="!scope.row.requestable" src="../../../../assets/images/cuo.png" style="width: 20px;height: 20px" />
          </template>
        </el-table-column>
        <el-table-column width="155" label="订单编号" align="center" prop="order_number"  sortable />
        <el-table-column label="采购日期" align="center" prop="purchase_date" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.purchase_date, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column width="155" label="采购价格" align="center" prop="purchase_cost"  sortable />
        <el-table-column width="200" label="借出操作" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              :disabled="scope.row.qty <= scope.row.checkout_qty"
              :loading="exportLoading"
              @click="changeInOut(scope.row)"
            >借出</el-button>
          </template>
        </el-table-column>
        <el-table-column  fixed="right" width="155" label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['admin:assets:consumables:put']"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              v-hasPermi="['admin:assets:consumables:delete']"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <div v-if="step === 2">
      <detail :top-id="topId" :choose-item="chooseItem" @fanhui="fanhui"></detail>
    </div>
    <!-- 添加或修改消耗品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="编号" prop="item_no">
          <el-input v-model="form.item_no" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="消耗品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入消耗品名称" />
        </el-form-item>
        <el-form-item label="数量" prop="qty">
          <el-input v-model="form.qty" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="采购日期" prop="purchase_date">
          <el-date-picker
            v-model="form.purchase_date"
            clearable
            size="small"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择采购日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="采购价格" prop="purchase_cost">
          <el-input v-model="form.purchase_cost" placeholder="请输入采购价格" />
        </el-form-item>
        <el-form-item label="订单编号" prop="order_number">
          <el-input v-model="form.order_number" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="最小数量" prop="min_amt">
          <el-input v-model="form.min_amt" placeholder="请输入最小数量" />
        </el-form-item>
        <el-form-item label="型号" prop="model_number">
          <el-input v-model="form.model_number" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="form.notes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="是否可申请" prop="requestable">
          <el-switch
            v-model="form.requestable"
            active-color="#13ce66"
            inactive-color="#f1f1f1"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="地址">
          <ChooseLocation :rqParam = "form.location" @commitLocationMethod="commitLocationMethod"></ChooseLocation>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类类型" clearable size="small">
            <el-option
              v-for="dict in categoriesList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="制造商" prop="manufacturer">
          <el-select v-model="form.manufacturer" placeholder="请选择制造商" clearable size="small">
            <el-option
              v-for="dict in manufacturersList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-select v-model="form.supplier" placeholder="请选择供应商" clearable size="small">
            <el-option
              v-for="dict in suppliersList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="图片上传">
          <el-button
            type="primary"
            plain
            icon="el-icon-upload"
            size="mini"
            @click="imageUpload"
          >图片上传
          </el-button>
          <img v-if="form.image" :src="form.image" class="avatar">
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 图片上传 -->
    <el-dialog :title="title1" :visible.sync="open1" width="400px" append-to-body @close="open1 = false">
      <FileUpload ref="saveFile" :file-type="['ALL']" @input="fileGet" />
    </el-dialog>
    <Borrow ref="borrow" :borrow-show="itemChoose" asset-type="consumable" @commitData="submitFormOutIn"></Borrow>
    <InputFile ref="inputfile" @inputFile="inputFile"></InputFile>
  </div>
</template>

<script>
import {
  listConsumables,
  getConsumables,
  delConsumables,
  addConsumables,
  updateConsumables,
  exportConsumables,
  importsConsumables
} from "@/api/vadmin/assets/consumables";
import FileUpload from "@/components/FileUpload/index";
import { listCategories } from "@/api/vadmin/basic/categories";
import { listManufacturers } from "@/api/vadmin/basic/manufacturers";
import { listSuppliers } from "@/api/vadmin/basic/suppliers";
import detail from "./detail";
import { listUser } from "@/api/vadmin/permission/user";
import Borrow from "@/views/components/Borrow";
import ChooseLocation from "@/views/components/ChooseLocation";
import InputFile from "@/views/components/InputFile";

export default {
  name: "Consumables",
  components: { InputFile, FileUpload, detail, Borrow, ChooseLocation },
  data() {
    return {
      itemChoose: null,
      openOutOrin: false,
      titleOutOrin: "",
      topId: 0,
      chooseItem: null,
      step: 1,
      title1: "",
      open1: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 消耗品表格数据
      consumablesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        item_no: null,
        name: null,
        qty: null,
        requestable: null,
        purchase_date: null,
        purchase_cost: null,
        order_number: null,
        min_amt: null,
        model_number: null,
        image: null,
        notes: null,
        category_id: null,
        manufacturer_id: null,
        supplier_id: null
      },
      // 表单参数
      form: {},
      manufacturersList: [],
      categoriesList: [],
      suppliersList: [],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "消耗品名称不能为空", trigger: "blur" }
        ],
        qty: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ]
      },
      outOrin: {
        consumable: undefined,
        qty: 0,
        assigned_to: undefined,
        notes: undefined
      },
      rulesOutIn: {
        assigned_to: [
          { required: true, message: "请先选中用户", trigger: "change" }
        ],
        qty: [
          { required: true, message: "数量不能为空", trigger: "blur" },
          { min: 1, message: "最小借出数量不能小于", trigger: "blur" }
        ]
      },
      roleList: [],
      queryData: null
    };
  },
  created() {
    this.queryData = this.$route.query;
    this.step = 1;
    listUser().then(response => {
      this.roleList = response.data.results;
    });
    this.getCategoriesList();
    this.getSuppliers();
    this.getMaufacturersList();
    this.getList();
  },
  methods: {
    handleInput() {
      this.$refs.inputfile.open();
    },
    inputFile(val) {
      // 是否更新已经存在的用户数据
      importsConsumables(val).then(response => {
        this.$alert("导入成功！", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      });
    },
    commitLocationMethod(val) {
      this.form.location = val;
    },
    refreshList() {
      this.getList();
    },
    changeInOut(item) {
      this.itemChoose = item;
      this.$refs.borrow.$nextTick(() => {
        this.$refs.borrow.open();
      });
    },
    submitFormOutIn() {
      this.$message({
        message: "借出成功",
        type: "success"
      });
      this.$refs.borrow.close();
      this.getList();
    },
    clickAssets(scope) {
      this.chooseItem = scope.row;
      this.step = 2;
      this.topId = scope.row.id;
    },
    fanhui() {
      this.step = 1;
      this.refreshList();
    },
    getCategoriesList() {
      this.loading = true;
      listCategories().then(response => {
        this.categoriesList = response.data.results;
        this.loading = false;
      });
    },
    getMaufacturersList() {
      this.loading = true;
      listManufacturers().then(response => {
        this.manufacturersList = response.data.results;
        this.loading = false;
      });
    },
    getSuppliers() {
      this.loading = true;
      listSuppliers().then(response => {
        this.suppliersList = response.data.results;
        this.loading = false;
      });
    },
    fileGet(file) {
      this.open1 = false;
      this.$refs.saveFile.fileList = [];
      this.form.image = file;
    },
    imageUpload() {
      this.open1 = true;
      this.title1 = "图片上传";
    },
    /** 查询消耗品列表 */
    getList() {
      this.loading = true;
      listConsumables(this.queryParams).then(response => {
        this.consumablesList = response.data.results;
        this.total = response.data.count;
        this.loading = false;
        if (this.queryData != undefined && this.queryData) {
          if (this.queryData.key === "add") {
            this.handleAdd();
          }
          if (this.$route.path !== "/assets/consumables") {
            this.$router.replace("/assets/consumables");
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        description: null,
        modifier: null,
        dept_belong_id: null,
        update_datetime: null,
        create_datetime: null,
        item_no: null,
        name: null,
        deleted_datetime: null,
        qty: null,
        requestable: null,
        purchase_date: null,
        purchase_cost: null,
        order_number: null,
        min_amt: null,
        model_number: null,
        image: null,
        notes: null,
        category_id: null,
        creator_id: null,
        manufacturer_id: null,
        supplier_id: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加消耗品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getConsumables(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改消耗品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateConsumables(this.form).then(response => {
              this.$message({
                message: "修改成功",
                type: "success"
              });
              this.open = false;
              this.getList();
            });
          } else {
            addConsumables(this.form).then(response => {
              this.$message({
                message: "新增成功",
                type: "success"
              });
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delConsumables(ids).then(res => {
          this.getList();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        });
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有附属品据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportConsumables(queryParams);
      }).then(response => {
        this.download(response.data.file_url, response.data.name);
      });
    }
  }
};
</script>
<style>
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  margin-top: 15px;
}
</style>
